//
//  FlipsideViewController.m
//  CommuteWarriorUtility
//
//  Created by Rohit Mathews on 5/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FlipsideViewController.h"

static NSString* OPERATE_ON_BATTERY = @"Operate_On_Battery";
static NSString* MIN_BATTERY_LVL = @"Minimum_Battery_Level";

@implementation FlipsideViewController

@synthesize delegate;
@synthesize operateOnBattery;
@synthesize minimumBatteryLevel;
@synthesize batteryLevelLabel;

- (void)setValuesForControls {
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if([userDefaults objectForKey:OPERATE_ON_BATTERY] != nil){
		[operateOnBattery setOn:[userDefaults boolForKey:OPERATE_ON_BATTERY]];
	}
	else{
		[operateOnBattery setOn:NO];
	}
	if([userDefaults objectForKey:MIN_BATTERY_LVL] != nil){
		[minimumBatteryLevel setValue:[userDefaults floatForKey:MIN_BATTERY_LVL]];
		NSString *labelText = [NSString stringWithFormat:@"%.0f%@", minimumBatteryLevel.value, @"%"];
		batteryLevelLabel.text = labelText;
	}
	else{
		[minimumBatteryLevel setValue:50.0];
	}
}
	
- (void)viewDidLoad {
    [super viewDidLoad];
	[minimumBatteryLevel setMinimumValue:0.0];
	[minimumBatteryLevel setMaximumValue:100.0];
	[minimumBatteryLevel addTarget:self action:@selector(updateBatteryLevelLabel:) 
	   forControlEvents:UIControlEventValueChanged];
	[self setValuesForControls];
}

- (IBAction)done:(id)sender {
	[self.delegate flipsideViewControllerDidFinish:self];
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	[userDefaults setBool:[operateOnBattery isOn] forKey:OPERATE_ON_BATTERY];
	[userDefaults setFloat:minimumBatteryLevel.value  forKey:MIN_BATTERY_LVL];
	NSLog(@"Preferences modified. Operate on Battery : %s; Min Battery Level : %.0f",
		  [operateOnBattery isOn]? "true":"false", minimumBatteryLevel.value);
}

- (IBAction)updateBatteryLevelLabel:(id)sender {
	NSString *labelText = [NSString stringWithFormat:@"%.0f%@", minimumBatteryLevel.value, @"%"];
	batteryLevelLabel.text = labelText;
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (void)dealloc {
	[operateOnBattery release];
	[minimumBatteryLevel release];
	[batteryLevelLabel release];
    [super dealloc];
}


@end
